package com.shujia

object Demo28Match {
  def main(args: Array[String]): Unit = {

    /**
     * 模式匹配
     * 1、基本数据类型
     * 2、字符串
     * 3、枚举
     * 4、样例类
     * 5、匹配类型
     */


    //1、基本数据类型
    val i: Int = 20

    i match {
      case 10 => println("i等于10")
      case 20 => println("i等于20")
      case _ => println("其他")
    }

    //2、匹配字符串
    val str: String = "java"

    str match {
      case "hadoop" => println("str等于hadoop")
      case "hive" => println("str等于hive")
      case "scala" => println("str等于scala")
      case _ => println("其他")
    }

    //3、匹配类型
    val obj: Any = true

    obj match {
      case i: Int => println(s"是一个int类型：${i}")
      case s: String => println(s"是一个String类型：${s}")
      case d: Double => println(s"是一个Double类型：${d}")
      case _ => println(s"其他类型：$obj")
    }

    //4、匹配样例类
    case class User(id: String, name: String, age: Int)

    val user: User = User("001", "张三", 25)

    user match {
      case User("001", "张三", 23) => println("001")
      case User("002", "李四", 24) => println("002")
      case User("003", "王五", 25) => println("003")
      case _ => println("其他")
    }


    //模式匹配应用
    val users: List[(String, String, Int)] = List(
      ("001", "张三", 23),
      ("002", "李四", 24),
      ("003", "王五", 25),
      ("004", "赵六", 26),
      ("005", "小伟", 27)
    )
    //对每个人的年龄加1
    users.map(user => {
      val id: String = user._1
      val name: String = user._2
      val age: Int = user._3
      (id, name, age + 1)
    })

    //使用模式匹配简化上面的代码
    val result: List[(String, String, Int)] = users.map {
      case (id, name, age) =>
        (id, name, age + 1)
    }

    result.foreach(println)


  }

}
